package org.example.Soution003;

import java.util.Stack;

public class StringDecode {
    public static void main(String[] args) {
        String str="abc3[cd]xyz";
        StringDecode obj=new StringDecode();
        System.out.println(obj.decodeString(str));
    }

    public String decodeString(String s) {
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        StringBuilder result = new StringBuilder();
        StringBuilder tempStr=new StringBuilder();
        boolean isExist=false;
        for (char c : chars) {
            if(c=='['){
                stack.push(c);
                isExist=true;
            }else if(c==']'){
                StringBuilder temp=new StringBuilder();
                while(stack.peek()!='['){
                    temp.append(stack.pop());
                }
                temp=temp.reverse();
                stack.pop();//去掉‘[’
                StringBuilder temp2=new StringBuilder();
                while(!stack.isEmpty()&&stack.peek()-'0'>=0&&stack.peek()-'9'<=0){
                    temp2.append(stack.pop());
                }
                temp2=temp2.reverse();
                int num=Integer.parseInt(temp2.toString());
                int time=num==0?1:num;
                for(int i=0;i<time;i++){
                    tempStr.append(temp);
                }
                if(stack.isEmpty()){
                    result.append(tempStr);
                    isExist=false;
                }else{
                    for(int i=0;i<tempStr.length();i++){
                        stack.push(tempStr.charAt(i));
                    }
                }
                tempStr.setLength(0);
                temp.trimToSize();
            }else if(!isExist&&(c-'a'>=0)){
                result.append(c);
            }else{
                stack.push(c);
            }
        }
        return result.toString();
    }
}
